#!/usr/bin/python3

""" This script simulate a PC wechat client to get wechat sports data """

import re
import json
import requests

# Headers: simulate wechat embedded browser
HEADERS = {
    'Connection': 'keep-alive',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
    'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko)'
                  ' Chrome/39.0.2171.95 Safari/537.36 MicroMessenger/6.5.2.501'
                  ' NetType/WIFI WindowsWechat QBCore/3.43.27.400 QQBrowser/9.0.2524.400',
    'Accept-Encoding': 'gzip, deflate'
}

COOKIES = {
    'hwstepranksk': 'OelfW0wGPj13NByeYrs3hmGEBUaarmYZ2O4GG4XFcwlt08nj'
}

REQUEST_URL = 'https://hw.weixin.qq.com/steprank/step/personal'

def get_info(openid):
    """Get data according to openid"""
    params = {"openid": openid}
    data = requests.get(url=REQUEST_URL, params=params, cookies = COOKIES, headers=HEADERS)
    data.encoding = "utf-8"
    try:
        return parse_code(data.text)
    except LookupError:
        return {"Error": "Cookies could be out of date"}


def parse_code(code):
    """Parse web page source code"""
    match_strings = re.findall(r"window.json = (\S+);", code)
    # json strings are hided in js code
    if len(match_strings) == 0:
        raise LookupError
    else:
        json_string = match_strings[0]
    json_object = json.loads(json_string)
    data_dict = {
        "openid": json_object.get("myopenid"),
        "Today Steps": json_object.get("rankdesc").get("score"),
        "History Steps": json_object.get("rankdetaillist")[0].get("score"),
        "Highest Record": json_object.get("rankdetaillist")[1].get("score")
    }
    return data_dict


if __name__ == "__main__":
    print(get_info("o95gOt6gGIfTROCYQajbVCfFr9BA"))